import { ref, Ref } from 'vue'
import { loadTencentMapSDK } from './loadTencentMapSDK'
import { loadDistrictData } from './districtData'
import { TENCENT_MAP_CONFIG } from './config'

export interface MapOptions {
  center: { lat: number; lng: number }
  zoom: number
  mapStyle: string
  showDistricts: boolean
  enableDrag: boolean
  enableZoom: boolean
}

export interface DistrictBoundary {
  name: string
  level: 'province' | 'city' | 'district'
  adcode: string
  boundaries: any[]
}

export function useTencentMap() {
  const map: Ref<any> = ref(null)
  const isMapReady = ref(false)
  const districtLayers: Ref<any[]> = ref([])
  const districtClickCallback = ref<Function | null>(null)
  const mapClickCallback = ref<Function | null>(null)

  /**
   * 初始化地图
   */
  const initMap = async (container: HTMLElement, options: MapOptions) => {
    try {
      // 加载腾讯地图SDK
      const TMap = await loadTencentMapSDK()
      
      if (!TMap) {
        throw new Error('腾讯地图SDK加载失败')
      }

      // 创建地图实例
      map.value = new TMap.Map(container, {
        center: new TMap.LatLng(
          options.center?.lat || TENCENT_MAP_CONFIG.defaultCenter.lat,
          options.center?.lng || TENCENT_MAP_CONFIG.defaultCenter.lng
        ),
        zoom: options.zoom || TENCENT_MAP_CONFIG.defaultZoom,
        mapStyleId: options.mapStyle || TENCENT_MAP_CONFIG.defaultMapStyle,
        draggable: options.enableDrag !== false && TENCENT_MAP_CONFIG.events.enableDrag,
        scrollable: options.enableZoom !== false && TENCENT_MAP_CONFIG.events.enableZoom,
        doubleClickZoom: options.enableZoom !== false && TENCENT_MAP_CONFIG.events.enableDoubleClickZoom,
        mapZoomType: (options.enableZoom !== false && TENCENT_MAP_CONFIG.events.enableZoom) ? TMap.constants.MAP_ZOOM_TYPE.RANGE : TMap.constants.MAP_ZOOM_TYPE.DISABLE,
        baseMap: {
          type: 'vector',
          features: ['base'],
          
        }
      })

      isMapReady.value = true

      // 如果需要显示行政区划边界
      if (options.showDistricts) {
        await loadDistrictBoundaries()
      }

      console.log('腾讯地图初始化成功')
      return map.value
    } catch (error) {
      console.error('地图初始化失败:', error)
      throw error
    }
  }

  /**
   * 加载行政区划边界
   */
  const loadDistrictBoundaries = async () => {
    try {
      if (!map.value) {
        throw new Error('地图实例未初始化')
      }

      console.log('开始加载行政区划边界...')
      // 获取行政区划数据
      const districtData = await loadDistrictData()
      
      // 清除现有图层
      clearDistrictLayers()

      // 添加省级边界
      for (const province of districtData.provinces) {
        const layer = await addDistrictLayer(province)
        if (layer) {
          districtLayers.value.push(layer)
        }
      }

      console.log(`行政区划边界加载完成，共加载 ${districtLayers.value.length} 个省份`)
    } catch (error) {
      console.error('行政区划边界加载失败:', error)
      throw error
    }
  }

  /**
   * 添加行政区划图层
   */
  const addDistrictLayer = async (district: DistrictBoundary) => {
    try {
      if (!map.value) return null

      const TMap = (window as any).TMap
      if (!TMap) return null

      // 创建多边形图层
      const polygon = new TMap.MultiPolygon({
        map: map.value,
        geometries: district.boundaries.map((boundary: any) => ({
          paths: boundary,
          styleId: 'district-style'
        })),
        styles: {
          'district-style': new TMap.PolygonStyle({
            color: 'rgba(65, 105, 225, 0.15)', // 半透明蓝色填充
            strokeColor: '#4169E1', // 皇家蓝边框
            strokeWidth: 1.5,
            strokeDashArray: [0] // 实线
          })
        }
      })

      // 绑定点击事件
      polygon.on('click', (event: any) => {
        console.log('点击了行政区划:', district.name)
        // 触发行政区划点击事件
        if (districtClickCallback.value) {
          districtClickCallback.value({
            district,
            event,
            position: event.latLng
          })
        }
      })

      return polygon
    } catch (error) {
      console.error('添加行政区划图层失败:', error)
      return null
    }
  }

  /**
   * 清除行政区划图层
   */
  const clearDistrictLayers = () => {
    districtLayers.value.forEach(layer => {
      if (layer && layer.setMap) {
        layer.setMap(null)
      }
    })
    districtLayers.value = []
  }

  /**
   * 设置地图中心点
   */
  const setCenter = (lat: number, lng: number) => {
    if (map.value && isMapReady.value) {
      const TMap = (window as any).TMap
      map.value.setCenter(new TMap.LatLng(lat, lng))
    }
  }

  /**
   * 设置地图缩放级别
   */
  const setZoom = (zoom: number) => {
    if (map.value && isMapReady.value) {
      map.value.setZoom(zoom)
    }
  }

  /**
   * 放大地图
   */
  const zoomIn = () => {
    if (map.value && isMapReady.value) {
      const currentZoom = map.value.getZoom()
      map.value.setZoom(currentZoom + 1)
    }
  }

  /**
   * 缩小地图
   */
  const zoomOut = () => {
    if (map.value && isMapReady.value) {
      const currentZoom = map.value.getZoom()
      map.value.setZoom(currentZoom - 1)
    }
  }

  /**
   * 获取当前缩放级别
   */
  const getZoom = (): number => {
    if (map.value && isMapReady.value) {
      return map.value.getZoom()
    }
    return 0
  }

  /**
   * 设置地图边界
   */
  const fitBounds = (bounds: any) => {
    if (map.value && isMapReady.value) {
      map.value.fitBounds(bounds)
    }
  }

  /**
   * 设置行政区划点击回调
   */
  const setDistrictClickCallback = (callback: Function | null) => {
    districtClickCallback.value = callback
  }

  /**
   * 设置地图点击回调
   */
  const setMapClickCallback = (callback: Function | null) => {
    mapClickCallback.value = callback
  }

  /**
   * 获取点击位置信息
   */
  const getClickInfo = (event: any) => {
    if (!map.value || !event.latLng) return null
    
    return {
      position: {
        lat: event.latLng.lat,
        lng: event.latLng.lng
      },
      pixel: event.pixel,
      event: event
    }
  }

  /**
   * 获取地图中心点
   */
  const getCenter = () => {
    if (map.value && isMapReady.value) {
      const center = map.value.getCenter()
      return {
        lat: center.lat,
        lng: center.lng
      }
    }
    return null
  }

  /**
   * 获取地图边界
   */
  const getBounds = () => {
    if (map.value && isMapReady.value) {
      return map.value.getBounds()
    }
    return null
  }

  /**
   * 启用/禁用地图拖拽
   */
  const setDraggable = (draggable: boolean) => {
    if (map.value && isMapReady.value) {
      map.value.setOptions({ draggable })
    }
  }

  /**
   * 获取拖拽事件信息
   */
  const getDragInfo = (event: any) => {
    const center = getCenter()
    const bounds = getBounds()
    
    return {
      center,
      bounds,
      event
    }
  }

  /**
   * 销毁地图
   */
  const destroyMap = () => {
    if (map.value) {
      clearDistrictLayers()
      map.value.destroy()
      map.value = null
      isMapReady.value = false
    }
  }

  return {
    map,
    isMapReady,
    initMap,
    loadDistrictBoundaries,
    clearDistrictLayers,
    setCenter,
    setZoom,
    zoomIn,
    zoomOut,
    getZoom,
    getCenter,
    getBounds,
    setDraggable,
    getDragInfo,
    fitBounds,
    setDistrictClickCallback,
    setMapClickCallback,
    getClickInfo,
    destroyMap
  }
}